/**
 * Project Name:cnsy-url-short-service
 * File Name:RequestInteceptor.java
 * Package Name:cn.cnsy123.shorturls.api.interceptor 
 * Date: 2020年4月14日-下午3:39:59
 * Copyright (c) 2020, yangpengfei@360@126.com All Rights Reserved. 
 *
 */

package cn.cnsy123.shorturls.api.interceptor;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

import cn.cnsy123.shorturls.api.controller.result.SysMenuResult;
import cn.cnsy123.shorturls.api.controller.vo.TreeMenuVo;
import cn.cnsy123.shorturls.business.localuser.ConsoleUserVo;
import cn.cnsy123.shorturls.business.service.SysMenuService;
import cn.cnsy123.shorturls.business.util.TreeMenuUtil;
import cn.cnsy123.shorturls.business.util.UserAgentUtil;
import cn.cnsy123.shorturls.constants.SessionInfoConstants;

/**
 * ClassName: RequestInteceptor
 * 
 * @author yangpengfei
 * @date 2020年4月14日-下午3:39:59
 * @version 1.0
 * @since JDK 1.7
 */
public class RequestInteceptor extends HandlerInterceptorAdapter {

    private static final Logger logger = LoggerFactory.getLogger(RequestInteceptor.class);
    @Autowired
    private SysMenuService sysMenuService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        if (handler instanceof HandlerMethod) {
            ConsoleUserVo sessionCacheInfo = (ConsoleUserVo) request.getSession()
                    .getAttribute(SessionInfoConstants.SESSION_USER_BEAN);
            if (sessionCacheInfo != null) {
                boolean ajaxRequest = UserAgentUtil.isAjaxRequest(request);
                if (!ajaxRequest) {
                    List<TreeMenuVo> treeMenus = sysMenuService.selectTreeMenuByUserId(sessionCacheInfo.getUserId());
                    if (!CollectionUtils.isEmpty(treeMenus)) {
                        logger.info("当前用户的菜单权限:{}", JSON.toJSONStringWithDateFormat(treeMenus, "yyyy-MM-dd HH:mm:ss",
                                SerializerFeature.WriteDateUseDateFormat, SerializerFeature.WriteMapNullValue));
                        request.getSession().setAttribute("treeMenus", treeMenus);
                        logger.info("sessionId:{}", request.getSession().getId());

                        Object selectNode = request.getSession().getAttribute(SessionInfoConstants.SESSION_VISIT_NODE);
                        if (selectNode == null) {
                            SysMenuResult firstPageNode = TreeMenuUtil.getFirstPageNode(treeMenus);
                            request.getSession().setAttribute(SessionInfoConstants.SESSION_VISIT_NODE,
                                    firstPageNode.getId());
                            request.getSession().setAttribute(SessionInfoConstants.SESSION_VISIT_NODE_ADDR,
                                    firstPageNode.getMenuUrl());
                        }
                        logger.info("当前节点:【{}】",
                                request.getSession().getAttribute(SessionInfoConstants.SESSION_VISIT_NODE));
                        Map<String, SysMenuResult> indexData = TreeMenuUtil.convertDataById(treeMenus);
                        List<Long> pids = TreeMenuUtil.getParentId(indexData,
                                Long.valueOf(request.getSession().getAttribute("cur").toString()));
                        if (!CollectionUtils.isEmpty(pids)) {
                            request.getSession().setAttribute("res", "," + StringUtils.join(pids.toArray(), ",") + ",");
                            logger.info("当前节点的父节点:[{}]", StringUtils.join(pids.toArray(), ","));
                        }

                    }
                }
            }
        }
        return true;
    }

}
